const http = require('http');

const port = process.env.PORT || 3000;

const server = http.createServer((req, res) => {
  const { method, url } = req;

  // GET /api/hello - existing simple JSON endpoint
  if (method === 'GET' && url === '/api/hello') {
    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify({ message: 'Hello from simple-node-app', time: new Date().toISOString() }));
    return;
  }

  // GET /api/time - returns server time and uptime
  if (method === 'GET' && url === '/api/time') {
    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify({ time: new Date().toISOString(), uptime: process.uptime() }));
    return;
  }

  // POST /api/echo - echoes back JSON body
  if (method === 'POST' && url === '/api/echo') {
    let body = '';
    req.on('data', chunk => { body += chunk; });
    req.on('end', () => {
      let parsed = null;
      try {
        parsed = body ? JSON.parse(body) : null;
      } catch (err) {
        res.writeHead(400, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify({ ok: false, error: 'Invalid JSON' }));
        return;
      }

      res.writeHead(200, { 'Content-Type': 'application/json' });
      res.end(JSON.stringify({ ok: true, youSent: parsed }));
    });
    return;
  }

  // Default root page
  res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
  res.end(
    `<h1>Simple Node App</h1>
    <ul>
      <li><a href="/api/hello">/api/hello</a> - simple JSON</li>
      <li><a href="/api/time">/api/time</a> - server time + uptime</li>
    </ul>
    <p>Use <code>POST /api/echo</code> with a JSON body to test echo.</p>`
  );
});

server.listen(port, () => {
  console.log(`Server running at http://localhost:${port}/`);
});

process.on('SIGINT', () => {
  console.log('Shutting down...');
  server.close(() => process.exit(0));
});
